let mysql = require('mysql');
let connection;
function connect() {
    connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '123456',
        database : 'db_bt'
    });
    connection.connect();
    connection.on('error', err => {
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            connect();
        }
    });
}
connect();
function save(data) {
    let count = data.files.length
    if(count === 0) count = 1
    let extname = []
    data.files.forEach(file => {
        const m = file.name.match(/\.([a-zA-Z\d]+)$/)
        if(m) {
            const ext = m[1].toLowerCase()
            if(!extname.includes(ext)) {
                extname.push(ext)
            }
        }
    })
    if(extname.length === 0) {
        const m = data.name.match(/\.([^.]+)$/)
        if(m) extname.push(m[1].toLowerCase())
    }
    let sql = `insert into tb_file(id, name, filesize, filenums, extname) value("${data.infohash}", "${data.name}", ${data.length}, ${count}, "${extname.join()}")`;
    connection.query(sql);
}



module.exports = save;